<?php

namespace App\Task;

use AlibabaCloud\Vcs\V20200515\VcsApiResolver;
use App\Model\DataBackhaulSetting;
use App\Model\DataPaymentBackhaul;
use App\Model\DataSpread;
use App\Model\PlayletBind;
use App\Model\Payment;
use App\Model\SystemOrderDay;
use App\Model\SystemOrderDayCount;
use GuzzleHttp\Client;
use Hyperf\Crontab\Annotation\Crontab;
use Hyperf\DbConnection\Db;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\ApplicationContext;
use Psr\Log\LoggerInterface;



//#[Crontab(name: "dayPaymentStatisticsTask", rule: "0 1 * * *", callback: "execute", memo: "统计除今日之前的订单所有数据'")]
class CpsStatisticsTask
{
    protected LoggerInterface $logger;
    public function __construct(protected LoggerFactory $loggerFactory)
    {
        $this->logger = $this->loggerFactory->get('log', 'dayStatistics');
    }

    public function execute()
    {
        $container = ApplicationContext::getContainer();
        $redis = $container->get(\Hyperf\Redis\RedisFactory::class)->get('default');
        $this->logger->info(date('Y-m-d H:i:s') . '------------------------获取一段时间内的所有订单数据');
        $startDate = date('Y-m-d 00:00:00',strtotime("-1 day"));
        $endDate = date("Y-m-d 23:59:59",strtotime("-1 day"));

        $this->logger->info('开始时间为：'.$startDate);
        $this->logger->info('结束时间为：'.$endDate);
        try {
            $orderKey =  'cps_run';
            $keyData = $redis->get($orderKey);
            if(!empty($keyData)){
//                $redis->del($orderKey);
                $this->logger->info('存在处理中的订单进程');
                $this->logger->info(date('Y-m-d H:i:s') . '------------------------结束定时获取订单进行上报');
                return;
            }else{
                $redis->set($orderKey,1);
            }
            $this->statisticsCPS();
            $this->logger->info('运行CPS');
            $redis->del($orderKey);

        }catch (\Exception $e){
            $redis->del($orderKey);
            $this->logger->error('请求订单|错误：' . $e->getLine() . '|' . $e->getMessage());
        }
        $this->logger->info(date('Y-m-d H:i:s') . '------------------------结束定时获取订单数据');
    }



    //统计CPS数据
    public function statisticsCPS(){

        $this->logger->info(date('Y-m-d H:i:s') . '------------------------获取3天内的统计数据');
        $startDate = date('Y-m-d',1711900800);
        $endDate = date("Y-m-d",1715011200);


        $selectArr = ['date','playlet_id',
            Db::raw('SUM(order_pay_count) as order_pay_count'),
            Db::raw('SUM(order_wx_pay_count) as order_wx_pay_count'),
            Db::raw('SUM(order_virtually_pay_count) as order_virtually_pay_count'),
            Db::raw('SUM(order_wx_pay_amonut) as order_wx_pay_amonut'),
            Db::raw('SUM(order_virtually_pay_amount) as order_virtually_pay_amount'),
            Db::raw('SUM(dy_pay_count) as dy_pay_count'),
            Db::raw('SUM(dy_pay_amount) as dy_pay_amount'),
        ];
        $groupBy = ['date','playlet_id'];
        $this->logger->info('时间为：',[$startDate,$endDate]);
        $orderData = SystemOrderDay::query()->select($selectArr)
            ->whereIn('playlet_id',[91,92])
            ->whereBetween('date',[$startDate,$endDate])
            ->groupBy($groupBy)
            ->get()->toArray();

        //获取所有短剧的配置
        $bindData = PlayletBind::query()->select(['playlet_id','amount'])->get();

        if(!empty($bindData)){
            $bindKeyVal =array();
            foreach ($bindData as $bindDatum){
                $bindKeyVal[$bindDatum->playlet_id] = $bindDatum->amount;
            }
        }

        foreach ($orderData as $orderDatum){

            //判断是否存在这个数据
            $orderRes = SystemOrderDayCount::query()->where(['date' => $orderDatum['date'],'playlet_id' => $orderDatum['playlet_id']])->exists();

            if(!$orderRes){

                if(!empty($bindKeyVal[$orderDatum['playlet_id']])){
                    $amount = $bindKeyVal[$orderDatum['playlet_id']]/100;
                }else {
                    $amount = 1;
                }

                $order_wx_pay_amonut = ceil($orderDatum['order_wx_pay_amonut']/100*$amount);
                $order_virtually_pay_amount = ceil($orderDatum['order_virtually_pay_amount']/100*$amount);
                $order_pay_count = ceil($orderDatum['order_pay_count']*$amount); //支付订单数量
                $order_wx_pay_count = ceil($orderDatum['order_wx_pay_count']*$amount);
                $order_virtually_pay_count = ceil($orderDatum['order_virtually_pay_count']*$amount);
                //抖音支付
                $dy_pay_amount = ceil($orderDatum['dy_pay_amount']/100*$amount);
                $dy_pay_count = ceil($orderDatum['dy_pay_count']*$amount); //支付订单数量
                $order_amount  = $order_wx_pay_amonut+$order_virtually_pay_amount+$dy_pay_amount;
//
//                    $order_wx_pay_amonut = $orderDatum['order_wx_pay_amonut']/100;
//                    $order_virtually_pay_amount = $orderDatum['order_virtually_pay_amount']/100;
//                    $order_pay_count = $orderDatum['order_pay_count']; //支付订单数量
//                    $order_wx_pay_count = $orderDatum['order_wx_pay_count'];
//                    $order_virtually_pay_count = $orderDatum['order_virtually_pay_count'];
//                    $order_amount  = $order_wx_pay_amonut+$order_virtually_pay_amount;

//                }
                $insertData = [
                    'date' => $orderDatum['date'],
                    'playlet_id' => $orderDatum['playlet_id'],
                    'order_pay_count' => $order_pay_count, //支付订单数量
                    'order_wx_pay_count' => $order_wx_pay_count, //微信支付金额
                    'order_virtually_pay_count' => $order_virtually_pay_count, //虚拟支付金额
                    'order_wx_pay_amonut' => $order_wx_pay_amonut,//微信支付数量
                    'order_virtually_pay_amount' => $order_virtually_pay_amount,//虚拟支付数量
                    'dy_pay_count' => $dy_pay_count,//虚拟支付数量
                    'dy_pay_amount' => $dy_pay_amount,//虚拟支付数量
                    'order_amount' => $order_amount,//虚拟支付数量
                ];
                SystemOrderDayCount::create($insertData);

            }
        }

//        return true;

    }

    public function countOrder($statisData,$arrName,$spread_id,$playlet_id,$ad_id,$applet_id){

        $keyName = $spread_id.'|###|'.$playlet_id.'|###|'.$ad_id.'|###|'.$applet_id;

        if (!empty($statisData[$keyName][$arrName])) {
            $statisData[$keyName][$arrName] += 1;
        } else {
            $statisData[$keyName][$arrName] = 1;
        }
        return $statisData;
    }
    public function countOrderAmount($statisData,$arrName,$spread_id,$playlet_id,$ad_id,$applet_id,$amonut){

        $keyName = $spread_id.'|###|'.$playlet_id.'|###|'.$ad_id.'|###|'.$applet_id;

        if (!empty($statisData[$keyName][$arrName])) {
            $statisData[$keyName][$arrName] += $amonut;
        } else {
            $statisData[$keyName][$arrName] = $amonut;
        }
        return $statisData;
    }
}